package net.huashitong.ssydt.provider.alipay.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import net.huashitong.ssydt.exceptions.ServiceException;
import net.huashitong.ssydt.money.entity.SsMoneyOrder;
import net.huashitong.ssydt.provider.alipay.config.AlipayAppConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author <a href="mailto:yhy23456@163.com">huiyang.yu</a>
 * @since 2017.08.17
 */
@Service
@Transactional
public class AlipayServiceImpl implements AlipayService  {

    private AlipayAppConfig alipayAppConfig;

    @Autowired
    public AlipayServiceImpl(AlipayAppConfig alipayAppConfig) {
        this.alipayAppConfig = alipayAppConfig;
    }

    @Override
    public String orderForApp(SsMoneyOrder ssMoneyOrder) {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                alipayAppConfig.getAppID(), alipayAppConfig.getPrivatekey(), "json",
                alipayAppConfig.getInputCharset(), alipayAppConfig.getAlipayPublicKey(), "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。
        // 以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
//        model.setBody("华仕通教育-时事订单");//非必选
        model.setSubject(String.format("%s - 华仕通教育", ssMoneyOrder.getOrderName()));
        model.setOutTradeNo(ssMoneyOrder.getOrderId());
        model.setTimeoutExpress("30m");
        model.setTotalAmount(ssMoneyOrder.getOrderPrice().toString());
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(alipayAppConfig.getNotifyUrl());
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody();//就是orderString 可以直接给客户端请求，无需再做处理。
        } catch (AlipayApiException e) {
            throw new ServiceException("发起支付宝支付失败", e);
        }
    }

}
